﻿using System;
using System.Collections.Generic;
using System.Linq;
using NDBGen.Configuration;
using NDBGen.Plugins.DataAccess;

namespace NDBGen.Plugins.Reflexive
{
    [DataAccessCodeGenerator("Reflexive")]
    public class ReflexiveDataAccessCodeGenerator : FileGeneratorBase<DataAccessGeneratorPluginData>, IDataAccessCodeFileGenerator
    {
        public void WriteContextType(IEnumerable<Table> tables, String rootNamespace, IIndentedTextWriter writer)
        {
        }

        private String lastSchema;

        public void WriteModel(SchemaDataAccessOutputElement config, Table table, IIndentedTextWriter writer)
        {
            if (table.Schema != lastSchema)
            {
                writer.WriteLine(table.Schema);
                lastSchema = table.Schema;
            }

            using (writer.Indent())
            {
                writer.Write(table.Name);
                if (table.Descriptors.Any())
                {
                    writer.Write('|');
                    foreach (var token in table.Descriptors)
                    {
                        writer.Write(token);
                    }
                }
                writer.WriteLine();

                using (writer.Indent())
                {
                    foreach (var column in table.Columns)
                    {
                        writer.WriteLine(column.ToString());
                    }
                }
            }
        }

        public String GetModelOutputFilePath(SchemaDataAccessOutputElement config, Table table)
        {
            return config.Settings.Get("outputPath").Value;
        }

        public String GetContextOutputFilePath(SchemaDataAccessOutputElement config, String schemaName)
        {
            return config.Settings.Get("outputPath").Value;
        }

        public Boolean CanGenerateContextType
        {
            get { return false; }
        }
    }
}